package com.photoeditor.demo.ui.activity.subscribe;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.Purchase;
import com.billing.base.BillingManager;
import com.billing.base.IBillingProvider;
import com.billing.base.SimpleBillingUpdateListener;
import com.common.commercialize.utils.SubEventUtil;
import com.photoeditor.R;
import com.photoeditor.demo.app.TestUser;
import com.photoeditor.demo.app.XActivity;
import com.photoeditor.demo.model.event.PurchasesUpdatedEvent;
import com.photoeditor.demo.model.event.SubscribeSuccessEvent;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.model.subscribe.manager.SVipConstant;
import com.photoeditor.demo.model.subscribe.manager.SVipController;
import com.photoeditor.demo.model.subscribe.manager.SkuManager;
import com.photoeditor.demo.model.subscribe.manager.VipStatisticUtil;
import com.photoeditor.demo.model.subscribe.strategy.SVipStrategyManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.util.AppFrontBackHelper;
import com.photoeditor.demo.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.ButterKnife;

/**
 * Created by Lai on 2018/10/25 0025.
 */
public abstract class BaseSubscribeActivity extends XActivity implements VipStatisticUtil.IVipStatistic {

    public static final String EXTRA_STATISTICS_ENTRANCE = "EXTRA_S_E_N";
    public static final String EXTRA_STATISTICS_ENTRANCE_FUNCTIONS = "EXTRA_S_E_N_F";
    public static final String EXTRA_STATISTICS_ENTRANCE_STATISTIC = "EXTRA_S_E_S";
    public static final String EXTRA_START_MAIN = "EXTRA_S_MN";
    public static final String EXTRA_TYPE = "A";
    public static final String EXTRA_IS_RETAIN ="RETAIN";
    public static final String EXTRA_IS_FUNCTION_SUBSCRIBE ="FUNCTION_SUBSCRIBE";




    protected static SVipController.OnSubscribeCloseListener sOnSubscribeCloseListener;

    protected String mStatisticsEntrance;
    protected String entranceFunctions;
    protected String type;
    private boolean isRetain;
    private boolean isFunctionSubscribe;
    private int payColorType;
    private int desColorType;
    protected IBillingProvider mIBillingProvider;

    private TextView tvDialogTip;
    private TextView tvBottomTip;
    private TextView tvFirstTip;
    private TextView tvSecondTip;

    protected VipStatisticUtil mStatisticUtil;

    public String sku;

    protected boolean mVisible;

    protected boolean mHasClickButton = false;

    protected boolean mFirstSuccessUpdate = true;
    protected final Object mLock = new Object();

    private SimpleBillingUpdateListener mSimpleBillingUpdateListener = new SimpleBillingUpdateListener() {

        @Override
        public void onPurchasesUpdated(List<Purchase> list) {
            super.onPurchasesUpdated(list);
            checkPurchaseUpdate(list);
        }

        @Override
        public void onBillingResultCodeReturn(int i) {
            super.onBillingResultCodeReturn(i);
            int subscribeType;
            if (i != BillingClient.BillingResponseCode.OK && mVisible) {
                if (mHasClickButton) {
                    subscribeType = SVipStrategyManager.getInstance().getFirstSubscribeType();
                    mStatisticUtil.statisticFail(sku,i,subscribeType == SkuManager.TYPE_MONTHLY ? StatisticsConstant.VALUE_SUB_PACK_MONTH : StatisticsConstant.VALUE_SUB_PACK_YEAR,entranceFunctions);
                    onPurchaseFail();
                    if (i == 100) {
                        ToastUtil.showToast(R.string.vip_error_toast_gp);
                        VipStatisticUtil.statisticGoogleError();
                    } else {
                        ToastUtil.showToast(R.string.vip_error_toast);
                    }

                    if (i == BillingClient.BillingResponseCode.USER_CANCELED) {
                        onPurchaseFailUserCancel();
                    }
                }

                if (mStatisticsEntrance == null) {  //挽留
                    SVipStrategyManager.getInstance().getFirstSubscribeType();
//                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_RETAIN_FAIL,
//                            StatisticsConstant.KEY_SUB_PACK, subscribeType == SkuManager.TYPE_MONTHLY ? StatisticsConstant.VALUE_SUB_PACK_MONTH : StatisticsConstant.VALUE_SUB_PACK_YEAR,
//                            StatisticsConstant.KEY_SUB_FAIL_REASON, "" + i,
//                            StatisticsConstant.KEY_AB_TYPE, type);
                } else {
//                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SUB_FAIL,
//                            StatisticsConstant.KEY_SUB_PACK, subscribeType == SkuManager.TYPE_MONTHLY ? StatisticsConstant.VALUE_SUB_PACK_MONTH : StatisticsConstant.VALUE_SUB_PACK_YEAR,
//                            StatisticsConstant.KEY_ENTER_SUB, mStatisticsEntrance,
//                            StatisticsConstant.KEY_SUB_FAIL_REASON, "" + i,
//                            StatisticsConstant.KEY_AB_TYPE, type);
                }
            }
        }

    };

    protected abstract int getContentLayoutId();

    protected abstract void initView();

    protected abstract boolean isPurchaseSuccess(List<Purchase> purchases);

    protected abstract void onPurchaseSuccess();

    protected void onPurchaseFail() {
    }

    /**
     * 订阅失败的情况之一：用户取消
     */
    protected void onPurchaseFailUserCancel() {

    }

    /**
     * 界面的统计字段
     *
     * @return
     */
    @Override
    public abstract String getStatisticPageStr();

    @Override
    public String getStatisticEntranceStr() {
        return mStatisticsEntrance;
    }

    @Override
    public boolean statisticSubPageShowAndClick() {
        return false;
    }

    @Override
    public boolean isPageShowing() {
        return mVisible;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (AppVipManager.isVip()) {
            if (TestUser.isTestUser()) {
                ToastUtil.showToast("already Vip!");
            }
            finish();
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        setContentView(getContentLayoutId());
        ButterKnife.bind(this);

        initView();
        initData();

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        EventBus.getDefault().register(this);

        if (mStatisticsEntrance == null) {  //挽留窗口
            mStatisticUtil.statisticShow(true);
            //StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SHOW_RETAIN,StatisticsConstant.KEY_AB_TYPE, type);
        } else {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SHOW_SUB, StatisticsConstant.KEY_ENTER_SUB, mStatisticsEntrance,
//                    StatisticsConstant.KEY_AB_TYPE, type);

            //非挽留弹窗统计
            mStatisticUtil.statisticShow(false);
            SPDataManager.showSubscribeActivity();
        }
    }

    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            mStatisticsEntrance = intent.getStringExtra(EXTRA_STATISTICS_ENTRANCE);
            entranceFunctions = intent.getStringExtra(EXTRA_STATISTICS_ENTRANCE_FUNCTIONS);
            type = intent.getStringExtra(EXTRA_TYPE);
            isRetain=intent.getBooleanExtra(EXTRA_IS_RETAIN,false);
            isFunctionSubscribe=intent.getBooleanExtra(EXTRA_IS_FUNCTION_SUBSCRIBE,false);
            tvDialogTip = findViewById(R.id.tv_vip_dialog_tip);//挽留弹窗
            tvBottomTip=findViewById(R.id.tv_vip_bottom_tip);//功能订阅页和主订阅页
            tvFirstTip=findViewById(R.id.tv_vip_first_tip);//月费介绍文案
            tvSecondTip=findViewById(R.id.tv_vip_second_tip);//年费介绍文案
            if(isRetain && !isFunctionSubscribe){//挽留弹窗（只有付费文案）
                payColorType =SVipStrategyManager.getInstance().getWitchColorPay(SVipConstant.VIP_ENTRANCE_RETAIN);
            }else if(!isRetain && isFunctionSubscribe){//功能订阅页(只有付费文案)
                payColorType =SVipStrategyManager.getInstance().getWitchColorPay(SVipConstant.VIP_ENTRANCE_FUNCTION_SUBSCRIBE);
            }else{//主订阅页(付费文案+介绍文案)
                payColorType =SVipStrategyManager.getInstance().getWitchColorPay(SVipConstant.VIP_ENTRANCE_IN_APP);
                desColorType =SVipStrategyManager.getInstance().getWitchColorDes(SVipConstant.VIP_ENTRANCE_IN_APP);
            }
            switch (payColorType) {//付费文案
                case SVipConstant.COLOR_DARK://付费介绍文案深色
                    if(isRetain && !isFunctionSubscribe){//挽留弹窗
                        SpUtils.obtain().save("payColor", 0xff3a3a87);
                        tvDialogTip.setTextColor(0xff3a3a87); //不能省略前面两个ff
                    }else{//主订阅页和功能订阅页
                        SpUtils.obtain().save("payColor", 0xff3a3a87);
                        tvBottomTip.setTextColor(0xff3a3a87); //不能省略前面两个ff
                    }
                    break;
                case SVipConstant.COLOR_LIGHT://付费介绍文案浅色
                    if(isRetain && !isFunctionSubscribe){
                        SpUtils.obtain().save("payColor", 0xffd0d0fb);
                        tvDialogTip.setTextColor(0xffd0d0fb); //不能省略前面两个ff
                    }else{
                        SpUtils.obtain().save("payColor", 0xffd0d0fb);
                        tvBottomTip.setTextColor(0xffd0d0fb); //不能省略前面两个ff
                    }
                    break;
                default:
                    if(isRetain && !isFunctionSubscribe){
                        SpUtils.obtain().save("payColor", 0xff3a3a87);
                        tvDialogTip.setTextColor(0xff3a3a87); //不能省略前面两个ff
                    }else{
                        SpUtils.obtain().save("payColor", 0xff3a3a87);
                        tvBottomTip.setTextColor(0xff3a3a87); //不能省略前面两个ff
                    }
                    break;
            }
            if(!isRetain && !isFunctionSubscribe){//主订阅页才有介绍文案
                switch (desColorType) {//介绍文案
                    case SVipConstant.COLOR_DARK://介绍文案深色
                        tvFirstTip.setTextColor(0xff3a3a87); //不能省略前面两个ff
                        tvSecondTip.setTextColor(0xff3a3a87); //不能省略前面两个ff
                        break;
                    case SVipConstant.COLOR_LIGHT://介绍文案浅色
                        tvFirstTip.setTextColor(0xffb5b5d5); //不能省略前面两个ff
                        tvSecondTip.setTextColor(0xffb5b5d5); //不能省略前面两个ff
                        break;
                    default:
                        tvFirstTip.setTextColor(0xff3a3a87); //不能省略前面两个ff
                        tvSecondTip.setTextColor(0xff3a3a87); //不能省略前面两个ff
                        break;
                }
            }

        }

        mStatisticUtil = new VipStatisticUtil(this);

        BillingManager.getInstance().addBillingUpdatesListener(mSimpleBillingUpdateListener);
        mIBillingProvider = BillingManager.getInstance().getBillingProvider();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mVisible = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        mVisible = false;
        if (mStatisticUtil != null && AppFrontBackHelper.getInstant().isAppBackground()) {
            mStatisticUtil.statisticLeave();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mStatisticUtil.onDestroy();
        BillingManager.getInstance().removeBillingUpdatesListener(mSimpleBillingUpdateListener);
        if (sOnSubscribeCloseListener != null) {
            sOnSubscribeCloseListener.onSubscribeClose();
            sOnSubscribeCloseListener = null;
        }
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);

        if (mStatisticsEntrance == null) {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_CLOSE_RETAIN,
//                    StatisticsConstant.KEY_AB_TYPE, type);
        } else {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_CLOSE_SUB, StatisticsConstant.KEY_ENTER_SUB, mStatisticsEntrance,
//                    StatisticsConstant.KEY_AB_TYPE, type);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        statisticBack(false);
    }

    protected void statisticBack(boolean isRetainDialog) {
        mStatisticUtil.statisticExit(isRetainDialog);
    }

    protected void statisticCloseClick() {
        mStatisticUtil.statisticCloseClick();
    }

    protected void subscribe(String sku, String clickStatistic) {
        this.sku=sku;
        mHasClickButton = true;
        mStatisticUtil.statisticClick(sku,clickStatistic,isRetain);

        if (TestUser.isTestUser()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            // builder.setIcon(R.drawable.ic_launcher);//设置图标
            // 为对话框设置取消按钮
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    // 购买失败
                    onPurchaseFailUserCancel();
                    builder.create().dismiss();
                }
            });

            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    // 购买成功
                    SPDataManager.setIsSvipSwithOn(true);
                    SubEventUtil.uploadSubscribeEvent(sku, sku+"_token", sku+"_id", getStatisticEntranceStr());
                    onPurchaseSuccess();

                    finish();
                    EventBus.getDefault().post(new SubscribeSuccessEvent(SubscribeSuccessEvent.SUB_TYPE_BUY));

                    int subscribeType = SVipStrategyManager.getInstance().getFirstSubscribeType();
                    if (mStatisticsEntrance == null) {
//                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_RETAIN_SUCCESS, "subPack", subscribeType == SkuManager.TYPE_MONTHLY ? "month" : "annual",
//                        StatisticsConstant.KEY_AB_TYPE, type);
                    } else {
                        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SUB_SUCCESS,
                                StatisticsConstant.KEY_SUB_PACK, subscribeType == SkuManager.TYPE_MONTHLY ? StatisticsConstant.VALUE_SUB_PACK_MONTH : StatisticsConstant.VALUE_SUB_PACK_YEAR,
                                StatisticsConstant.KEY_ENTER_SUB, mStatisticsEntrance,
                                StatisticsConstant.KEY_AB_TYPE, type,
                                StatisticsConstant.KEY_SKU,sku);
                    }

                    builder.create().dismiss();

                }
            });
            builder.create().show();// 使用show()方法显示对话框

        } else {
            mIBillingProvider.initiatePurchaseFlow(this
                    , sku
                    , BillingClient.SkuType.SUBS);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPurchasesUpdatedEvent(PurchasesUpdatedEvent event) {
        checkPurchaseUpdate(event.getPurchaseList());
    }

    protected void checkPurchaseUpdate(List<Purchase> list) {
        synchronized (mLock) {
            try {
                if (mFirstSuccessUpdate && isPurchaseSuccess(list)) {
                    if (mHasClickButton && mVisible) {
                        mStatisticUtil.statisticSuccess(list.get(list.size() - 1).getSku(),entranceFunctions);
                        StatisticsUtils.statisticAF(list,
                                getStatisticPageStr()
                                        + StatisticsConstant.STATISTIC_UNDERLINE
                                        + getStatisticEntranceStr());

                        StatisticsUtils.updateUserProperty(StatisticsConstant.PROPERTY_KEY_IF_SUB,
                                StatisticsConstant.PROPERTY_VALUE_SUB);
                        onPurchaseSuccess();
                    }
                    finish();
                    EventBus.getDefault().post(new SubscribeSuccessEvent(SubscribeSuccessEvent.SUB_TYPE_BUY));
                    mFirstSuccessUpdate = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected  void hideBottomUIMenu(){
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
//                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }


}
